package com.winway.framework.mybatis;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;

import javax.sql.DataSource;

/**
 * 数据源配置
 */
@Slf4j
@Configuration
public class DataSourceConfig {

    private final Environment environment;

    public DataSourceConfig(Environment environment) {
        this.environment = environment;
    }

    /**
     * 主数据源
     */
    @Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource masterDataSource() {
        boolean isDev = environment.acceptsProfiles(Profiles.of("dev", "test"));
        log.info("初始化主数据源，当前环境: {}", isDev ? "开发/测试" : "生产");
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * 只有在配置了spring.datasource.slave的情况下才启用从库
     */
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties("spring.datasource.slave")
    @ConditionalOnProperty(prefix = "spring.datasource", name = "slave.url")
    public DataSource slaveDataSource() {
        log.info("发现从库配置，初始化从数据源");
        return DruidDataSourceBuilder.create().build();
    }
}
